package com.meviewer.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.GeolocationPermissions;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.os.EnvironmentCompat;
import androidx.documentfile.provider.DocumentFile;

import com.alibaba.fastjson.JSONObject;
import com.meviewer.R;
import com.meviewer.activity.file.browser.FileBrowserActivity;
import com.meviewer.common.Registry;
import com.meviewer.nt.JavaContext;
import com.meviewer.service.CameraService;
import com.meviewer.service.FindPosService;
import com.meviewer.service.GPSServiceWrapper;
import com.meviewer.service.ProcessingHPYService;
import com.meviewer.service.ProcessingPakService;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

/**
 * @author hanhaoran
 */
public class MainActivity extends BaseActivity {
    public static MainActivity __ginstance = null;
    private WebView webView;
    private String fileDirPath = Registry.getInstance().getAppStoragePath();// 得到外部存储卡的数据库的路径名
    private ProcessingPakService _processingPakService = new ProcessingPakService();
    private ProcessingHPYService _processingHPYService = new ProcessingHPYService();

    public WebView getWebView() {
        return webView;
    }

    public static MainActivity getInstance() {
        return __ginstance;
    }
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" };
    //存储地名json文件的目录
    private static final String sta_path = "/storage/emulated/0/mev/BaseData/file/FindPositionData";
    /*---------------------------相机--------------------------------------------------------------------*/
    private ImageView ivCamera;
    private ImageView ivPhoto;
    public static File photoData;
    // 拍照的requestCode
    private static final int CAMERA_REQUEST_CODE = 0x00000010;
    // 申请相机权限的requestCode
    private static final int PERMISSION_CAMERA_REQUEST_CODE = 0x00000012;
    /**
     * 用于保存拍照图片的uri
     */
    private Uri mCameraUri;

    /**
     * 用于保存图片的文件路径，Android 10以下使用图片路径访问图片
     */
    private String mCameraImagePath;

    /**
     *  是否是Android 10以上手机
     */
    private boolean isAndroidQ = Build.VERSION.SDK_INT >= 29;

    public String queryPakExtent(String path){
        Uri uri = Uri.parse(path);
        String[] pakList = uri.getPath().split(":");
        String[] pakNewList = new String[pakList.length - 1];
        for(int i = 0; i < pakNewList.length; ++i)
        {
            pakNewList[i] = pakList[0] + pakList[i+1];
        }
       return _processingPakService.queryExtent(pakNewList);
    }

    public String queryHPYExtent(String path){
        Uri uri = Uri.parse(path);
        String[] hpyList = uri.getPath().split(":");
        String[] hpyNewList = new String[hpyList.length - 1];
        for(int i = 0; i < hpyNewList.length; ++i)
        {
            hpyNewList[i] = hpyList[0] + hpyList[i+1];
        }

        return _processingHPYService.queryExtent(hpyNewList);
    }

    /**
     * 检查权限并拍照。
     * 调用相机前先检查权限。
     * @return
     */
    public void checkPermissionAndCamera() {
        int hasCameraPermission = ContextCompat.checkSelfPermission(getApplication(),
                Manifest.permission.CAMERA);
        if (hasCameraPermission == PackageManager.PERMISSION_GRANTED) {
            //有权限，调起相机拍照。
            try {
                openCamera();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            //没有权限，申请权限。
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},
                    PERMISSION_CAMERA_REQUEST_CODE);
        }

    }

    /**
     * 调起相机拍照
     * @return
     */
    public void openCamera() throws IOException {
        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 判断是否有相机
        if (captureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            Uri photoUri = null;

            if (isAndroidQ) {
                // 适配android 10
                photoUri = createImageUri();
                photoData = createImageFile();
            } else {
                try {
                    photoFile = createImageFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (photoFile != null) {
                    mCameraImagePath = photoFile.getAbsolutePath();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri
                        photoUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", photoFile);
                    } else {
                        photoUri = Uri.fromFile(photoFile);
                    }
                }
            }

            mCameraUri = photoUri;
            if (photoUri != null) {
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                startActivityForResult(captureIntent, CAMERA_REQUEST_CODE);
            }
        }
    }

    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     *
     * @return 图片的uri
     */
    private Uri createImageUri() {
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        } else {
            return getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
        }
    }
    /**
     * 创建保存图片的文件
     * @return
     * @throws IOException
     */
    private File createImageFile() throws IOException {
        String imageName = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        File tempFile = new File(storageDir, imageName);
        if (!Environment.MEDIA_MOUNTED.equals(EnvironmentCompat.getStorageState(tempFile))) {
            return null;
        }
        return tempFile;
    }

    /*------------------------------------------------------------------------------------------*/



    public void writeFile(DocumentFile pickedDir) {

        try {/*text / plain*/
            DocumentFile file = pickedDir.createFile("image/jpeg", "try2.jpg");

            OutputStream out = getContentResolver().openOutputStream(file.getUri());
            try {

                // write the image content

            } finally {
                out.close();
            }

        } catch (IOException e) {
            throw new RuntimeException("Something went wrong : " + e.getMessage(), e);
        }
    }


    public void testwrite(){
        try{
            File dirFile = new File("/storage/48BAD89FBAD88B38/p.json");
            boolean res = dirFile.createNewFile();
            res = false;
            String path = dirFile.getAbsolutePath();
            Log.println(0,"","");
            if(dirFile.canWrite()){
                int i = 0;
            }
        } catch (IOException e){

        }
    }

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        verifyStoragePermissions(this);
        /*打包后 assets/mev文件夹文件向设备中复制-------版本1*/
        final int currentVersion = 1;
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        int lastVersion = prefs.getInt("VERSION_KEY", 0);
        if (currentVersion > lastVersion) {
            //如果当前版本大于上次版本，该版本属于第一次启动 ......
            //将当前版本写入preference中，则下次启动的时候，据此判断，不再为首次启动
            prefs.edit().putInt("VERSION_KEY",currentVersion).apply();
            CopyAssets("mev",fileDirPath);
        }

        FindPosService.findGeoJsonDataOrJsonData1(new ArrayList<>(), sta_path);

        setContentView(R.layout.activity_main);
        AppPermissions.verifyAllNeededPermissions(this);
        Registry.getInstance().setApplicationContext(this.getApplicationContext());
        __ginstance = this;
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        webView = findViewById(R.id.web_view);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        webView.addJavascriptInterface(JavaContext.getInstance(), "JavaContext");
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAllowFileAccessFromFileURLs(true);
        webView.getSettings().setAllowContentAccess(true);
//        手势焦点
        webView.requestFocusFromTouch();



        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return true;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }


            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                Uri uri = request.getUrl();
                String host = uri.getHost();
                if(host != null && host.equals("mev.com"))
                {
                    String dataType = uri.getQueryParameter("datatype");
                    if(dataType != null)
                    {
                        if(dataType.equals("json"))
                        {
                            try {
                                String filePath = uri.getPath();
                                File file = new File(filePath);
                                InputStream inputStream = new FileInputStream(file);
                                return new WebResourceResponse("application/json", "utf-8", inputStream);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        else if(dataType.equals("image"))
                        {
                            try {
                                String filePath = uri.getPath();
                                File file = new File(filePath);
                                InputStream inputStream = new FileInputStream(file);
                                return new WebResourceResponse("image/png", "utf-8", inputStream);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        else if(dataType.equals("baseimagepak"))
                        {
                            String baseImagePath = fileDirPath + "BaseData/BaseImgeTiles.pak";
                            String x = uri.getQueryParameter("x");
                            String y = uri.getQueryParameter("y");
                            String z = uri.getQueryParameter("z");
                           return _processingPakService.processingPak_ImageTiles(baseImagePath, x, y, z);
                        }
                        else if(dataType.equals("imagepak"))
                        {
                            String[] pakList = uri.getPath().split(":");
                            if(pakList.length > 1)
                            {
                                String[] pakNewList = new String[pakList.length - 1];
                                for(int i = 0; i < pakNewList.length; ++i)
                                {
                                    pakNewList[i] = pakList[0] + pakList[i+ 1];
                                }
                                String x = uri.getQueryParameter("x");
                                String y = uri.getQueryParameter("y");
                                String z = uri.getQueryParameter("z");
                                return _processingPakService.fetchImageFromList(pakNewList, x, y, z);
                            }
                        }
                        else if(dataType.equals("dempak"))
                        {
                            String[] pakList = uri.getPath().split(":");
                            if(pakList.length > 1)
                            {
                                String lastStr = pakList[pakList.length - 1];
                                if(!lastStr.endsWith("layer.json"))
                                {
                                    int slashOccurence = 0;
                                    int i = lastStr.length() - 1;
                                    for(; i >= 0; --i)
                                    {
                                        if(lastStr.charAt(i) == '/')
                                        {
                                            ++slashOccurence;
                                        }
                                        if(slashOccurence == 3)
                                        {
                                            break;
                                        }
                                    }
                                    pakList[pakList.length - 1] = lastStr.substring(0, i);
                                    String[] pakNewList = new String[pakList.length - 1];
                                    for(i = 0; i < pakNewList.length; ++i)
                                    {
                                        pakNewList[i] = pakList[0] + pakList[i+ 1];
                                    }
                                    String x = uri.getQueryParameter("x");
                                    String y = uri.getQueryParameter("y");
                                    String z = uri.getQueryParameter("z");
                                    return _processingPakService.fetchDEMFromList(pakNewList, x, y, z);
                                }
                                else
                                {
                                    int lastSlashIndex = lastStr.lastIndexOf("/");
                                    pakList[pakList.length - 1] = lastStr.substring(0, lastSlashIndex);
                                    String[] pakNewList = new String[pakList.length - 1];
                                    for(int i = 0; i < pakNewList.length; ++i)
                                    {
                                        pakNewList[i] = pakList[0] + pakList[i+ 1];
                                    }

                                    WebResourceResponse response = _processingPakService.fetchLayerJsonFromList(pakNewList);
                                    if(null != response)
                                    {
                                        return response;
                                    }
                                }

                            }

                        }
                        else if(dataType.equals("image_hpy"))
                        {
                            String path = uri.getPath();
                            String[] hpyList = path.split(":");
                            if(hpyList.length > 1)
                            {
                                String[] hpyNewList = new String[hpyList.length - 1];
                                for(int i = 0; i < hpyNewList.length; ++i)
                                {
                                    hpyNewList[i] = hpyList[0] + hpyList[i+ 1];
                                }
                                int x = Integer.parseInt(uri.getQueryParameter("x"));
                                int y = Integer.parseInt(uri.getQueryParameter("y"));
                                int z = Integer.parseInt(uri.getQueryParameter("z"));

                                String imageType = uri.getQueryParameter("imageType");
                                WebResourceResponse response = _processingHPYService.fetchImageFromList(hpyNewList, x, y, z, imageType);

                                if(null != response)
                                {
                                    return response;
                                }
                            }
                        }
                        else if(dataType.equals("dem_hpy"))
                        {
                            String path = uri.getPath();
                            String[] hpyList = path.split(":");
                            if(hpyList.length > 1)
                            {
                                String lastStr = hpyList[hpyList.length - 1];

                                if(!lastStr.endsWith("layer.json"))
                                {
                                    int slashOccurence = 0;
                                    int i = lastStr.length() - 1;
                                    for(; i >= 0; --i)
                                    {
                                        if(lastStr.charAt(i) == '/')
                                        {
                                            ++slashOccurence;
                                        }
                                        if(slashOccurence == 3)
                                        {
                                            break;
                                        }
                                    }
                                    hpyList[hpyList.length - 1] = lastStr.substring(0, i);
                                    String[] hpyNewList = new String[hpyList.length - 1];
                                    for(i = 0; i < hpyNewList.length; ++i)
                                    {
                                        hpyNewList[i] = hpyList[0] + hpyList[i+ 1];
                                    }
                                    int x = Integer.parseInt(uri.getQueryParameter("x"));
                                    int y = Integer.parseInt(uri.getQueryParameter("y"));
                                    int z = Integer.parseInt(uri.getQueryParameter("z"));

                                    WebResourceResponse response = _processingHPYService.fetchDEMFromList(hpyNewList, x, y, z);

                                    if(null != response)
                                    {
                                        return response;
                                    }
                                }
                                else
                                {
                                    int lastSlashIndex = lastStr.lastIndexOf("/");
                                    hpyList[hpyList.length - 1] = lastStr.substring(0, lastSlashIndex);
                                    String[] hpyNewList = new String[hpyList.length - 1];
                                    for(int i = 0; i < hpyNewList.length; ++i)
                                    {
                                        hpyNewList[i] = hpyList[0] + hpyList[i+ 1];
                                    }

                                    WebResourceResponse response = _processingHPYService.fetchLayerJsonFromList(hpyNewList);
                                    if(null != response)
                                    {
                                        return response;
                                    }
                                }
                            }
                        }
                    }

                }

                return super.shouldInterceptRequest(view, request);
            }
        });

        // 如下代码：
        // Worker 同步执行
        //        Http 同步获取 url  是否可以连接
        // 如果可以连通，说明是开发模式，则 webView 加载 url 页面
        // 如果不能连通，说明是单机模式，则 webView 加载 assets 页面
        //
        // 因此，可以将 url 修改为开发机器 vue 页面部署地址
        // 这样需要用到安卓机器看效果时，不需要打开 Android Studio，只需要开发机器和平板都处在同一局域网即可
        webView.loadUrl("file:///android_asset/index.html");
        /*  webView.loadUrl("http://192.168.43.152:8081");*/
        /*  webView.loadUrl("http://192.168.8.169:8081");*/
        /* webView.loadUrl("http://192.168.8.168:8081");*/
        /*       webView.loadUrl("http://192.168.43.154:8081");*/
        //webView.loadUrl("file:///storage/emulated/0/mev/web/index.html");
        /*  webView.loadUrl("http://192.168.43.60:8081");*/
        /*   webView.loadUrl("http://192.168.43.154:8081");*/
//        webView.loadUrl("http://192.168.8.102:8081");
        /*      webView.loadUrl("http://192.168.43.154:8081");*/
//        String url = "http://192.168.43.60:8081";
//        Worker.sync(
//                () -> Http.sync(new Request.Builder().url(url).head().build()),
//                res -> {
//                    if (Objects.isNull(res) || res.code() != HttpURLConnection.HTTP_OK) {
//                        webView.loadUrl("file:///android_asset/index.html");
//                    } else {
//                        webView.loadUrl(url);
//                    }
//                }
//        );

        //开启GPS
        //GPSServiceWrapper.getInstance().startService();

        webView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                callback.invoke(origin, true, false);
            }
        });

    }



    private static final int FILE_SELECT_CODE = 0;

    public void showFileChooser() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {

            startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE);

        } catch (android.content.ActivityNotFoundException ex) {
            Log.d("SELECT FILE", ex.getMessage());
        }
    }


    private static final String TAG = "ChooseFile";

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == FileBrowserActivity.ACTION_LOAD_FILE_BROWSER_CODE) {
            switch (resultCode) {
                case FileBrowserActivity.ACTION_LOAD_FILE_BROWSER_CODE: {
                    String jsContextFunctionName = data.getStringExtra(FileBrowserActivity.JS_CONTEXT_FUNCTION_NAME);
                    String filepath = data.getStringExtra(FileBrowserActivity.ARG_FILEPATH);
                    webView.evaluateJavascript("javascript:" + jsContextFunctionName + "('" + filepath + "')", null);
                    break;
                }

                default:
                    break;
            }
        }

        switch (requestCode) {
            case FILE_SELECT_CODE:
                if (resultCode == RESULT_OK) {
                    Uri uri = data.getData();
                    SelectFileHelper helper = new SelectFileHelper(this);
                    String path = helper.getPathFromUri(uri);

                    //webView.evaluateJavascript("javascript:JsContext.slotSelectGpsFile('" + gpsdata + "')",null);
                    webView.evaluateJavascript("javascript:JsContext.slotSelectGpsFile('" + path + "')", null);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);

        File photoFile = null;
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                if (isAndroidQ) {
                    //全图
                    File aa = new File(getRealPath(mCameraUri));
                    //File file = CameraService.getimage(getRealPath(mCameraUri),aa.getName());
                    mCameraImagePath = aa.getAbsolutePath();
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("sl",mCameraImagePath);
                jsonObject.put("all",mCameraImagePath);
                webView.evaluateJavascript("javascript:JsContext.getCameraPhoto('" + jsonObject.toJSONString() + "')", null);

            } else {
                System.out.println("取消");
                Toast.makeText(this,"取消",Toast.LENGTH_LONG).show();
            }
        }
    }

    private String getRealPath(Uri fileUrl) {
        String fileName = null;
        Uri filePathUri = fileUrl;
        if (fileUrl != null) {
            if (fileUrl.getScheme().toString().compareTo("content") == 0) {
                // content://开头的uri
                Cursor cursor = getContentResolver().query(fileUrl, null, null,
                        null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    int column_index = cursor.getColumnIndexOrThrow("_data");
                    fileName = cursor.getString(column_index); // 取出文件路径
                    if (!fileName.startsWith("/mnt")) {
                        // 检查是否有”/mnt“前缀

                        /* fileName = "/mnt" + fileName;*/
                    }
                    cursor.close();
                }
            } else if (fileUrl.getScheme().compareTo("file") == 0) {
                // file:///开头的uri
                fileName = filePathUri.toString();
                fileName = filePathUri.toString().replace("file://", "");
                // 替换file://
                if (!fileName.startsWith("/mnt")) {
                    // 加上"/mnt"头
                    fileName += "/mnt";
                }
            }
        }
        return fileName;
    }
    private void Copts(String assetDir)
    {
        File mWorkingPath = new File(assetDir);
        mWorkingPath.mkdirs();
    }
    /* private void CopyAssets(String assetDir, String dir) {
         String[] files;
         try {
             // 获得Assets一共有几多文件
             files = getAssets().list(assetDir);


         } catch (IOException e1) {
             return;
         }
         File mWorkingPath = new File(dir);
         // 如果文件路径不存在
         if (!mWorkingPath.exists()) {
             // 创建文件夹
             if (!mWorkingPath.mkdirs()) {
                 // 文件夹创建不成功时调用
             }
         }
         for (int i = 0; i < files.length; i++) {
             try {
                 // 获得每个文件的名字
                 String fileName = files[i];
                 // 根据路径判断是文件夹还是文件
                 if (!fileName.contains(".")) {
                     if (0 == assetDir.length()) {
                         CopyAssets(fileName, dir + fileName + "/");
                     } else {
                         CopyAssets(assetDir + "/" + fileName, dir + "/"
                                 + fileName + "/");
                     }
                     continue;
                 }
                 File outFile = new File(mWorkingPath, fileName);
                 if (outFile.exists())
                     outFile.delete();
                 InputStream in = null;
                 if (0 != assetDir.length()) {
                     in = getAssets().open(assetDir + "/" + fileName);
                 }
                 else {
                     in = getAssets().open(fileName);
                 }
                 OutputStream out = new FileOutputStream(outFile);
                 // Transfer bytes from in to out
                 byte[] buf = new byte[1024];
                 int len;
                 while ((len = in.read(buf)) > 0) {
                     out.write(buf, 0, len);
                 }
                 in.close();
                 out.close();
             } catch (FileNotFoundException e) {
                 e.printStackTrace();
             }
             catch (IOException e) {
                 e.printStackTrace();
             }
         }
         Copts(fileDirPath+"/Data");
     }*/
    private void CopyAssets(String assetDir, String dir) {
        String[] files;
        try {
            // 获得Assets一共有几多文件
            files = getAssets().list(assetDir);
        } catch (IOException e1) {
            return;
        }
        File mWorkingPath = new File(dir);
        // 如果文件路径不存在
        if (!mWorkingPath.exists()) {
            // 创建文件夹

            if (!mWorkingPath.mkdirs()) {
                // 文件夹创建不成功时调用
            }
        }
        for (int i = 0; i < files.length; i++) {
            try {
                // 获得每个文件的名字
                String fileName = files[i];
                // 根据路径判断是文件夹还是文件
                if (!fileName.contains(".")) {
                    if (0 == assetDir.length()) {
                        CopyAssets(fileName, dir + fileName + "/");
                    } else {
                        CopyAssets(assetDir + "/" + fileName, dir + "/"
                                + fileName + "/");
                    }
                    continue;
                }
                File outFile = new File(mWorkingPath, fileName);
                if (outFile.exists())
                    outFile.delete();
                InputStream in = null;
                if (0 != assetDir.length())
                    in = getAssets().open(assetDir + "/" + fileName);
                else
                    in = getAssets().open(fileName);
                OutputStream out = new FileOutputStream(outFile);
                // Transfer bytes from in to out
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                in.close();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*
     * android 动态权限申请
     * */
    public static void verifyStoragePermissions(Activity activity) {
        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(activity,
                    "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                System.out.println("没有写的权限");
                // 没有写的权限，去申请写的权限，会弹出对话框
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}